package com.aiti.lulian.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CardInquiryDto;
import com.aiti.lulian.entity.CommunicateInfo;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.entity.crad.CardInquiry;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CommunicateInfoMapper;
import com.aiti.lulian.mapper.card.crm.CrmCardInquiryMapper;
import com.aiti.lulian.service.ICommunicateInfoService;
import com.aiti.lulian.service.ICrmCardInquiryService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CrmCardInquiryServiceImpl extends BaseSerivceImpl<CrmCardInquiryMapper, CardInquiry> implements ICrmCardInquiryService {

    private final CrmCardInquiryMapper baseMapper;

    private final CloudShowManagerSubService cloudShowManagerSubService;

    private final ILuLianEnterpriseUserService enterpriseUserService;

    public CrmCardInquiryServiceImpl(CrmCardInquiryMapper baseMapper,CloudShowManagerSubService cloudShowManagerSubService,
                                     ILuLianEnterpriseUserService enterpriseUserService) {
        this.baseMapper = baseMapper;
        this.cloudShowManagerSubService =  cloudShowManagerSubService;
        this.enterpriseUserService = enterpriseUserService;
    }

    @Override
    public Map<String,Object> selectCrmInquiry(CardInquiryDto dto, String userId) {

        Message userInfo = cloudShowManagerSubService.getUserInfo(userId);
        if(userInfo.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
            throw new RuntimeException("当前登录人信息查询失败");
        }

        LinkedHashMap userInfoObj = (LinkedHashMap)userInfo.getObj();
        if(userInfoObj == null){
            throw new RuntimeException("当前登录人信息查询失败");
        }

        Message scopeInfo = cloudShowManagerSubService.queryUserAccessScope(userId);
        if(scopeInfo.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
            throw new RuntimeException("登录人权限查询失败");
        }

        String userScope = (String)scopeInfo.getObj();
        if(StringUtils.isBlank(userScope)){
            throw new RuntimeException("登录人权限查询失败");
        }

        Message userRoleMessage = cloudShowManagerSubService.getRoleByUserId(userId);
        if(userRoleMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
            throw new RuntimeException("查询用户失败");
        }

        String roles = (String)userRoleMessage.getObj();

        //如果userScope等于4表示有所有数据查看的权限

        CardInquiry cardInquiry = new CardInquiry();
        //查询当前部门下面的子级部门
        Set<String> deptIdArgs = new HashSet<>();
        switch (userScope){
            case "4":
                //如果是4是查看全公司的，这个里啥也不用做，在代码的后面把企业的ID写上就成
                if(StringUtils.isNotBlank(dto.getDeptId())){
                    deptIdArgs.add(dto.getDeptId());
                }
                break;
            case "3":
                String currentLoginDeptId = (String)userInfoObj.get("deptId");
                deptIdArgs.add(currentLoginDeptId);
                if(StringUtils.isNotBlank(dto.getDeptId()) || StringUtils.isNotBlank(currentLoginDeptId)){
                    //如果查询条件中选择了部门
                    String tempDeptId = currentLoginDeptId;
                    if(StringUtils.isNotBlank(dto.getDeptId())){
                        deptIdArgs.add(dto.getDeptId());
                        tempDeptId = dto.getDeptId();
                    }else{
                        deptIdArgs.add(currentLoginDeptId);
                    }
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(tempDeptId);
                    if(deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String obj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(obj)){
                        String[] split = obj.split(",");
                        for(String temp : split){
                            deptIdArgs.add(temp);
                        }
                    }
                }
                break;
            case "2":
                String ddeptId = (String)userInfoObj.get("deptId");
                deptIdArgs.add(ddeptId);
                break;
            case "1":
                cardInquiry.setDirector(userId);
                break;
            default:
                throw new RuntimeException("未查询到该用户的数据权限");
        }
//        boolean enterpriseAdmin = false;
//        if(StringUtils.isNotBlank(roles)){
//            String[] split = roles.split(",");
//            if(ArrayUtil.contains(split,"043ea2e3e02c4aa591df1f83e65069bc")){
//                enterpriseAdmin = true;
//            }
//        }



//        if(StringUtils.isNotBlank(dto.getDeptId()) || StringUtils.isNotBlank(currentLoginDeptId)){
//            //如果查询条件中选择了部门
//            String tempDeptId = currentLoginDeptId;
//            if(StringUtils.isNotBlank(dto.getDeptId())){
//                deptIdArgs.add(dto.getDeptId());
//                tempDeptId = dto.getDeptId();
//            }else{
//                deptIdArgs.add(currentLoginDeptId);
//            }
//            Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(tempDeptId);
//            if(deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
//                throw new RuntimeException("查询子级部门失败");
//            }
//            String obj = (String)deptMessage.getObj();
//            if(StringUtils.isNotBlank(obj)){
//                String[] split = obj.split(",");
//                for(String temp : split){
//                    deptIdArgs.add(temp);
//                }
//            }
//        }



//        if(enterpriseAdmin){
//            //如果是企业管理员则啥也不用设置
//            cardInquiry.setDirector(dto.getDirector());
//            if(StringUtils.isBlank(dto.getDeptId())){
//                deptIdArgs.clear();
//            }
//        }else{
////            String deptId = (String)userInfoObj.get("deptId");
//            if(StringUtils.isBlank(currentLoginDeptId)){
//                throw new RuntimeException("该用户没有绑定部门");
//            }
//            deptIdArgs.add(currentLoginDeptId);
//            String deptPermission = (String)userInfoObj.get("deptPermission");
//
//            if(StringUtils.isNotBlank(deptPermission)){
//                cardInquiry.setDirector(dto.getDirector());
//            }else{
//                //非部门负责人的逻辑
//                cardInquiry.setDirector(userId);
//            }
//        }

        cardInquiry.setLinkMan(dto.getLinkMan());
        cardInquiry.setFollowUpStatus(dto.getFollowUpStatus());
        cardInquiry.setDirector(dto.getDirector());

        //查询当前用户所邦定的企业
        LuLianEnterpriseUser enterpriseUser = enterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if(enterpriseUser == null){
            throw new RuntimeException("没有找到该用户绑定的企业");
        }

        cardInquiry.setEnterpriseId(enterpriseUser.getEnterpriseId());
        Integer pageNum = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        Page<CardInquiry> page = new Page<CardInquiry>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        List<CardInquiry> cardInquiries = baseMapper.selectCardInquiryList(page, cardInquiry,dto.getBeginDate(),dto.getEndDate(),dto.getOrderType(),deptIdArgs);

        //获取到所有的需要查询负责人的ID
        List<String> directorIds = cardInquiries.stream().filter(item -> StringUtils.isNotBlank(item.getDirector())).map(CardInquiry::getDirector).collect(Collectors.toList());
        if(directorIds != null && !directorIds.isEmpty()){
            Message message = cloudShowManagerSubService.getUsersInfo(directorIds);
            if(message.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                throw new RuntimeException("没有查询负责人Id");
            }
            LinkedHashMap directorUserInfoMap = (LinkedHashMap)message.getObj();
            for(CardInquiry temp : cardInquiries){
                LinkedHashMap o = (LinkedHashMap) directorUserInfoMap.get(temp.getDirector());
                if(o != null){
                    temp.setDirectorName((String) o.get("realname"));
                }
            }
        }

        long total = page.getTotal();
        Map<String,Object> result = new HashMap<>();
        result.put("total",total);
        result.put("data",cardInquiries);
        return result;
    }

    @Override
    public CardInquiry getCrmCardInquiry(CardInquiryDto dto) {
        CardInquiry one = getOne(new QueryWrapper<CardInquiry>().eq("base_id", dto.getBaseId()));
        if(one != null){
            Message userInfo = cloudShowManagerSubService.getUsersInfo(new ArrayList<String>(){{add(one.getDirector());}});
            if(userInfo.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                throw new RuntimeException("当前登录人信息查询失败");
            }

            LinkedHashMap userInfoObj = (LinkedHashMap)userInfo.getObj();
            if(userInfoObj == null){
                throw new RuntimeException("当前登录人信息查询失败");
            }
            LinkedHashMap o = (LinkedHashMap)userInfoObj.get(one.getDirector());
            if(o != null){
                one.setDirectorName((String) o.get("realname"));
            }

            if(StringUtils.isNotBlank(one.getDeptId())){
                Message deptNameByDeptId = cloudShowManagerSubService.getDeptNameByDeptId(one.getDeptId());
                if(deptNameByDeptId.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                    throw new RuntimeException("当前部门信息查询失败");
                }

                LinkedHashMap deptInfo = (LinkedHashMap)deptNameByDeptId.getObj();
                if(deptInfo == null){
                    throw new RuntimeException("当前部门信息查询失败");
                }
                String deptName = (String)deptInfo.get("baseName");
                one.setDeptName(deptName);
            }
        }
        return one;
    }

    @Override
    public Message queryEditRemovePre(String userId) {
        Message userRoleMessage = cloudShowManagerSubService.getRoleByUserId(userId);
        if(userRoleMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
            throw new RuntimeException("查询用户失败失败");
        }

        String roles = (String)userRoleMessage.getObj();

//        if(StringUtils.isNotBlank(roles)){
//            String[] split = roles.split(",");
//            if(ArrayUtil.contains(split,"043ea2e3e02c4aa591df1f83e65069bc")){
//                return true;
//            }
//        }

        Message userDeptQxMessage = cloudShowManagerSubService.getUserIsDeptQx(userId);
        if(userDeptQxMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
            throw new RuntimeException("当前部门信息查询失败");
        }
        LinkedHashMap obj = (LinkedHashMap)userDeptQxMessage.getObj();
        return Message.success(obj);
    }
}
